#include "mbappwig.h"
#include "ui_mbappwig.h"
#include <QHostAddress>
#include<QDebug>

//设备搜索页面
MbappWig::MbappWig(QWidget *parent) :
    QWidget(parent)
  , udpSocket(new QUdpSocket(this))
  , port(8888) // 监听和广播使用的端口
  ,ui(new Ui::MbappWig)
{
    ui->setupUi(this);
    // 初始化 UDP 套接字
    udpSocket->bind(port, QUdpSocket::ShareAddress);
    connect(udpSocket, &QUdpSocket::readyRead, this, &MbappWig::processPendingDatagrams);

    // 初始化表格
    ui->tableWidget->setColumnCount(3);
    ui->tableWidget->setHorizontalHeaderLabels(QStringList() << "设 备 名 称" << "状 态"<<"IP 地 址");
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 开始搜索按钮
    connect(ui->pushButton, &QPushButton::clicked, this, &MbappWig::startSearch);
}

MbappWig::~MbappWig()
{
    delete ui;
}

void MbappWig::addDeviceToTable(const QString &deviceName, const QString &ip, const QString &status)
{

    int row = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(row);
    ui->tableWidget->setItem(row, 0, new QTableWidgetItem(deviceName));
    ui->tableWidget->setItem(row, 1, new QTableWidgetItem(ip));
    ui->tableWidget->setItem(row, 2, new QTableWidgetItem(status));
}

void MbappWig::startSearch()
{
    qDebug()<<"正在搜索......"<<endl;
    QByteArray datagram = "SEARCH_DEVICE"; // 广播的内容
    udpSocket->writeDatagram(datagram, QHostAddress::Broadcast, port); // 发送广播包
}

void MbappWig::processPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(int(udpSocket->pendingDatagramSize()));
        QHostAddress sender;
        quint16 senderPort;

        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        // 假设接收到的信息格式为：设备名称|状态|IP
        QString data = QString::fromUtf8(datagram);
        QStringList deviceInfo = data.split('|');

        if (deviceInfo.size() == 3) {
            QString deviceName = deviceInfo[0];
            QString status = deviceInfo[1];
            QString ip = deviceInfo[2];
            if(status != tempName){
                tempName = status;
                // 添加设备信息到表格
                addDeviceToTable(deviceName, status, ip);
            }
        }
    }
}

